<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<script type="text/javascript">
// <![CDATA[
var imageTemplate = '<input type="hidden" name="{{file_field}}[image][{{id}}][image_id]" value="{{image_id}}" />'+
        '<div class="banner-image">'+
            '<div class="row">'+
                '<div id="{{file_field}}_{{id}}_file" class="uploader">'+
                    '<div id="{{file_field}}_{{id}}_file-old" class="file-row-info"><div id="{{file_field}}_preview_{{id}}" style="background:url({{thumbnail}}) no-repeat center;" class="image-placeholder"></div></div>'+
                    '<div id="{{file_field}}_{{id}}_file-new" class="file-row-info new-file"></div>'+
                    '<div class="buttons">'+
                        '<div id="{{file_field}}_{{id}}_file-install-flash" style="display:none">'+
                            '<?php echo $this->jsQuoteEscape(Mage::helper('media')->__('This content requires last version of Adobe Flash Player. <a href="%s">Get Flash</a>', 'http://www.adobe.com/go/getflash/')) ?>'+
                        '</div>'+
                    '</div>'+
                    '<div class="clear"></div>'+
                '</div>'+
            '</div>'+
            '<input type="hidden" class="validate-banner-file-{{id}}" id="{{file_field}}_{{id}}_file_save" name="{{file_field}}[image][{{id}}][file]" value="{{file_save}}" />'+
        '</div>';

function prepareImageItems(imageType, deviceId) {
    imageItems.application_id = deviceId;
    imageItems.itemCount = 0;
    imageItems.ulImages = $(imageType);
    imageItems.ulImagesId = imageType;
}

var imageItems = {
    ulImages : null,
    ulImagesId : null,
    application_id : null,
    fileUploadDir : '<?php echo Mage::getModel('xmlconnect/images')->getImageUrl('/') ?>',
    templateSyntax : /(^|.|\r|\n)({{(\w+)}})/,
    templateText : imageTemplate,
    itemCount : 0,
    excludedActionImages : ['<?php echo Mage_XmlConnect_Model_Device_Abstract::IMAGE_TYPE_ICON;?>',
        '<?php echo Mage_XmlConnect_Model_Device_Iphone::IMAGE_TYPE_PORTRAIT_BACKGROUND;?>',
        '<?php echo Mage_XmlConnect_Model_Device_Ipad::IMAGE_TYPE_PORTRAIT_BACKGROUND;?>',
        '<?php echo Mage_XmlConnect_Model_Device_Ipad::IMAGE_TYPE_LANDSCAPE_BACKGROUND;?>'],
    template: null,
    imageActionTruncateLenght: 35,
    add : function(config) {
        try {
            var isUploadedImage = true, uploaderClass = '';
            this.template = new Template(this.templateText, this.templateSyntax);

            config.ulImagesId = this.ulImagesId;

            if (!config.id) {
                config.id = this.itemCount;
                this.itemCount++;
            }
            if (!config.image_id) {
                config.image_id = 'uploader';
            }
            if (config.image_id == 'uploader') {
                isUploadedImage = false;
                uploaderClass = ' image-item-upload';
            } else {
                uploaderClass = ' image-item';
            }

            Element.insert(this.ulImages, {'bottom' : '<li id="pictureId_' + config.image_id  + '" class="' + uploaderClass  + '"></li>'});
            Element.insert(this.ulImages.down('li', config.id), {'bottom' : this.template.evaluate(config)});
            var container = $(config.file_field + '_' + config.id + '_file').up('li');

            if (config.show_uploader == 1) {
                config.file_save = [];

                new Downloadable.FileUploader(
                    config.file_field,
                    config.file_field + '_' + config.id,
                    container,
                    config.file_field + '[image][' + config.id + ']',
                    config.file_save,
                    config.file_field + '_' + config.id + '_file',
                    config
                );
            }

            if (config.image_id != 'uploader') {
                imageItems.addEditButton(container, config);
                imageItems.addDeleteButton(container, config);
            }
        } catch (e) {
            alert(e.message);
        }
    },
    addEditButton : function(container, config) {
        var actionAllowed = true;
        for (var i in imageItems.excludedActionImages) {
            if (imageItems.excludedActionImages[i] == config.file_field) {
                actionAllowed = false;
            }
        }

        if (config.image_id !== undefined && actionAllowed) {
            var edit_button_id = 'edit_link_' + config.image_id;
            var edit_button_state_id = 'edit_link_state' + config.image_id;
            var editButton = '';
            if (config.image_action_data !== undefined && config.image_action_data.entity_name !== undefined) {
                editButton += '<strong><?php echo $this->__('Action'); ?>:</strong> <a id="' + edit_button_id + '" href="#" class="edit-btn">' + (config.image_action_data.action_type + ', ' + config.image_action_data.entity_name).truncate(this.imageActionTruncateLenght) + '</a>';
            } else {
                editButton += '<strong><?php echo $this->__('Action'); ?>:</strong> <a id="' + edit_button_id + '" href="#" class="edit-btn"><?php echo $this->__('not set'); ?></a>';
            }
            Element.insert(container, { 'bottom' : editButton});
            imageItems.bindEditButton(edit_button_id, config);
        }
    },
    updateEditButtonState : function(config) {
        var edit_button_state_id = 'edit_link_' + config.image_id;
        if (config.image_action_data !== undefined) {
            $(edit_button_state_id).update((config.image_action_data.action_type + ', ' + config.image_action_data.entity_name).truncate(this.imageActionTruncateLenght))
        } else {
            $(edit_button_state_id).update('<?php echo $this->__('not set'); ?>')
        }
    },
    bindEditButton : function(edit_button_id, config) {
        try {
            $(edit_button_id).config = config;
            Event.observe(edit_button_id, 'click', this.editBanner.bind(this));
        } catch (e) {
            alert(e.message);
        }
    },
    addDeleteButton : function(container, config) {
        var delete_button_id = config.file_field + '_' + config.id + '_delete_button';

        if (config.image_id === undefined) {
            image_id = 0;
        } else {
            image_id = config.image_id;
        }

        var deleteButton = '<a href="#" onclick="imageItems.remove(' + image_id + '); return false;" id="' + delete_button_id + '" class="item-remove"><?php echo $this->__('Remove'); ?></a>';
        Element.insert(container, {'bottom' : deleteButton});
    },
    remove : function(image_id) {
        new Ajax.Request('<?php echo $this->getUrl('*/*/deleteimage')?>' + 'image_id/' + image_id + '/'
            + 'application_id/' +  imageItems.application_id + '/', {
            onSuccess : function(transport) {
                try {
                    if (transport.responseText.isJSON()) {
                        var response = transport.responseText.evalJSON()
                        if (response.error) {
                            alert(response.error);
                        } else {
                            imageItems.reloadImages(response.image_list);
                        }
                        if(response.ajaxExpired && response.ajaxRedirect) {
                            setLocation(response.ajaxRedirect);
                        }
                    } else {
                        alert(transport.responseText);
                    }
                } catch (e) {
                    alert(e.message);
                }
            }
        });
    },
    getImageListByType : function(image_type) {
        new Ajax.Request('<?php echo $this->getUrl('*/*/imagelist')?>' + 'image_type/' + image_type + '/'
            + 'application_id/' +  imageItems.application_id + '/', {
            onSuccess : function(transport) {
                try {
                    if (transport.responseText.isJSON()) {
                        var response = transport.responseText.evalJSON()
                        if (response.error) {
                            alert(response.error);
                        }
                        if(response.ajaxExpired && response.ajaxRedirect) {
                            setLocation(response.ajaxRedirect);
                        }
                        imageItems.reloadImages(response.image_list);
                    } else {
                        alert(transport.responseText);
                    }
                } catch (e) {
                    alert(e.message);
                }
            }
        });
    },
    reloadImages : function(image_list) {
        try {
            var imageType = image_list[0].file_field;
            Downloadable.unsetUploaderByType(imageType);
            var currentContainerId = imageType;
            var currentContainer = $(currentContainerId);
            var countOfNodes = 0;
            while (currentContainer.childNodes[0]) {
                ++countOfNodes;
                currentContainer.removeChild(currentContainer.childNodes[0]);
            }
            prepareImageItems(imageType, this.application_id);
            for (i=0; i < image_list.length; i++) {
                imageItems.add(image_list[i]);
            }
            imageItems.addDragDrop(imageType);
            updatePreview();
        } catch (e) {
            alert(e.message);
        }
    },
    addDragDrop : function (type) {
        var changeEffect;
        Sortable.create(type, { tag: 'li', only: 'image-item', overlap:'horizontal', constraint:false,
            onChange: function(item) {
                var list = Sortable.options(item).element;
            },

            onUpdate: function(list) {
                var newPositions = Sortable.sequence(list, arguments[1]).map( function(item) {
                    return item;
                });
                var i = 1,
                    data = {};

                newPositions.each( function(position) {
                    if (position != "uploader") {
                        data['data[' + position + ']'] = i;
                        i++;
                    }
                });

                data['type'] = type;
                data['application_id'] = imageItems.application_id;

                new Ajax.Request("<?php echo $this->getUrl('*/*/saveImageOrder')?>", {
                    method: "post",
                    parameters: data,
                    onSuccess: function (transport) {
                        if (transport.responseText.isJSON()) {
                            var response = transport.responseText.evalJSON()
                        }
                        imageItems.reloadImages(response.image_list);
                    }
                });
            }
        });
        if ($(type).select('.image-item-upload')[0]) {
            $(type).select('.image-item-upload')[0].stopObserving();
        }
    },
    editBanner : function (event) {
        try {
            var element = event.element();
            actionHelper.closeDialog();
            actionHelper.setImageElement(element);
            actionHelper.startDialog(element);
            event.preventDefault();
        } catch (e) {
            alert(e.message);
        }
    }
}

jscolor.dir = '<?php echo $this->getJsUrl(); ?>jscolor/';

var maxUploadFileSizeInBytes = <?php echo $this->getChild('media_uploader')->getDataMaxSizeInBytes() ?>;
var maxUploadFileSize = '<?php echo $this->getChild('media_uploader')->getDataMaxSize() ?>';

var uploaderTemplate = '<div class="no-display" id="[[idName]]-template">' +
                            '<div id="{{id}}" class="file-row file-row-narrow">' +
                                '<span class="file-info">' +
                                    '<span class="file-info-name">{{name}}</span>' + ' ' +
                                    '<span class="file-info-size">({{size}})</span>' +
                                '</span>' +
                                '<span class="progress-text"></span>' +
                                '<div class="clear"></div>' +
                            '</div>' +
                        '</div>' +
                        '<div class="no-display" id="[[idName]]-template-progress">' +
                            '{{percent}}% {{uploaded}} / {{total}}' +
                        '</div>';

var fileListTemplate = '<div style="background:url({{file}}) no-repeat center;" class="image-placeholder"></div>' +
                        '<span class="file-info">' +
                            '<span class="file-info-name">{{name}}</span>' + ' ' +
                            '<span class="file-info-size">({{size}})</span>' +
                        '</span>';

var Downloadable = {
    uploaderObj : $H({}),
    setUploaderObj : function(type, key, obj) {
        if (!this.uploaderObj.get(type)) {
            this.uploaderObj.set(type, $H({}));
        }
        this.uploaderObj.get(type).set(key, obj);
    },
    getUploaderObj : function(type, key){
        try {
            return this.uploaderObj.get(type).get(key);
        } catch (e) {
            try {
                console.log(e);
            } catch (e2) {
                alert(e.name + '\n' + e.message);
            }
        }
    },
    unsetUploaderObj : function(type, key) {
        try {
            this.uploaderObj.get(type).unset(key);
        } catch (e) {
            try {
                console.log(e);
            } catch (e2) {
                alert(e.name + '\n' + e.message);
            }
        }
    },
    unsetUploaderByType : function(type) {
        try {
            if (this.uploaderObj.get(type)) {
                this.uploaderObj.unset(type);
                this.uploaderObj.set(type, $H({}));
            }
        } catch (e) {
            try {
                console.log(e);
            } catch (e2) {
                alert(e.name + '\n' + e.message);
            }
        }
    },
    massUploadByType : function(type){
        try {
            this.uploaderObj.get(type).each(function(item){
                item.value.upload();
            });
        } catch (e) {
            try {
                console.log(e);
            } catch (e2) {
                alert(e.name + '\n' + e.message);
            }
        }
    }
};

Downloadable.FileUploader = Class.create();
Downloadable.FileUploader.prototype = {
    type : null,
    key : null, //key, identifier of uploader obj
    elmContainer : null, //insert Flex object and templates to elmContainer
    fileValueName : null, //name of field of JSON data of saved file
    fileValue : null,
    idName : null, //id name of elements for unique uploader
    uploaderText: uploaderTemplate,
    uploaderSyntax : /(^|.|\r|\n)(\[\[(\w+)\]\])/,
    uploaderObj : $H({}),
    config : null,
    initialize: function (type, key, elmContainer, fileValueName, fileValue ,idName, config) {
        this.type = type;
        this.key = key;
        this.elmContainer = elmContainer;
        this.fileValueName = fileValueName;
        this.fileValue = fileValue;
        this.idName = idName;
        this.config = config;
        uploaderTemplate = new Template(this.uploaderText, this.uploaderSyntax);

        Element.insert(
            elmContainer,
            {
                'top' : uploaderTemplate.evaluate({
                    'idName' : this.idName,
                    'fileValueName' : this.fileValueName,
                    'uploaderObj' : 'Downloadable.getUploaderObj(\'' + this.type + '\', \'' + this.key + '\')'
                })
            }
        );
        $(config.file_field + '_preview_' + config.id).update('<?php echo $this->__('Choose file'); ?>');
        if ($(this.idName + '_save')) {
            $(this.idName + '_save').value = this.fileValue.toJSON ? this.fileValue.toJSON() : Object.toJSON(this.fileValue);
        }
        Downloadable.setUploaderObj(
            this.type,
            this.key,
            new Flex.Uploader(this.idName, '<?php echo $this->getSkinUrl('media/uploaderSingle.swf') ?>', this.config)
        );
        new Downloadable.FileList(this.idName, Downloadable.getUploaderObj(type, key), this.config);

        if (varienGlobalEvents) {
            varienGlobalEvents.attachEventHandler('tabChangeBefore', Downloadable.getUploaderObj(type, key).onContainerHideBefore);
        }
    }
}

Downloadable.FileList = Class.create();
Downloadable.FileList.prototype = {
    file: [],
    containerId: '',
    container: null,
    uploader: null,
    fileListTemplate: fileListTemplate,
    templatePattern : /(^|.|\r|\n)({{(\w+)}})/,
    listTemplate : null,
    initialize: function (containerId, uploader, config) {
        this.containerId  = containerId,
        this.container = $(this.containerId);
        this.uploader = uploader;
        this.uploader.onFilesComplete = this.handleUploadComplete.bind(this);
        this.file = this.getElement('save').value.evalJSON();
        this.listTemplate = new Template(this.fileListTemplate, this.templatePattern);
        this.updateFiles();
        this.uploader.handleSelect = this.handleFileSelect.bind(this);
        this.uploader.onContainerHideBefore = this.handleContainerHideBefore.bind(this);
        this.uploader.config = config;
    },
    handleContainerHideBefore: function(container) {
        if (container && Element.descendantOf(this.uploader.container, container) && !this.uploader.checkAllComplete()) {
            if (!confirm('<?php echo $this->__('There are files that were selected but not uploaded yet. After switching to another tab your selections may be lost. Do you wish to continue ?');?>')) {
                return 'cannotchange';
            } else {
                return 'change';
            }
        }
    },
    handleFileSelect: function(event) {
        try {
            this.uploader.files = event.getData().files;
            this.uploader.checkFileSize();
            this.updateFiles();
            if (!hasTooBigFiles) {
                var uploaderList = $(this.uploader.flexContainerId);
                for (i = 0; i < uploaderList.length; i++) {
                    uploaderList[i].setStyle({visibility: 'hidden'});
                }
                Downloadable.massUploadByType(this.uploader.config.file_field);
            }
        } catch (e) {
            alert(e.message);
        }
    },
    getElement: function (name) {
        return $(this.containerId + '_' + name);
    },
    handleUploadComplete: function (files) {
        try {
            files.each(function(item) {
                if (!item.response.isJSON()) {
                    try {
                        console.log(item.response);
                    } catch (e2) {
                        alert(item.response);
                    }
                    return;
                }
                var response = item.response.evalJSON();
                if (response.error) {
                    imageItems.getImageListByType(this.uploader.config.file_field);
                    return;
                }
                var newFile = {};
                newFile.file = response.thumbnail;
                newFile.name = response.name;
                newFile.size = response.size;
                newFile.status = 'new';
                this.file[0] = newFile;
                this.uploader.removeFile(item.id);
                imageItems.reloadImages(response.image_list);
            }.bind(this));
            this.updateFiles();
        } catch (e) {
            alert(e.message);
        }
    },
    updateFiles: function() {
        try {
            this.getElement('save').value = this.file.toJSON ? this.file.toJSON() : Object.toJSON(this.file);
            this.file.each(function(row){
                row.size = this.uploader.formatSize(row.size);
                $(this.containerId + '-old').innerHTML = this.listTemplate.evaluate(row);
                $(this.containerId + '-new').hide();
                $(this.containerId + '-old').show();
            }.bind(this));
        } catch (e) {
            alert(e.message);
        }
    }
}
//]]>
</script>

<?php echo $this->getChildHtml('image_action_block');?>

<table border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td style="width:540px">
            <dl id="dl-image-accordion" class="accordion">
                <?php echo $this->getChildHtml('design_images'); ?>
            </dl>
            <?php echo $this->getChildHtml('design_accordion'); ?>
        </td>
        <td style="width:20px">&nbsp;</td>
        <td style="width:350px">
            <?php if ($this->canShowPreview()) : ?>
                <?php echo $this->getChildHtml('app_preview') ?>
            <?php endif; ?>
        </td>
    </tr>
</table>


